#
#  Copyright 2008 Garth Williams
#
#  This file is part of CommandPost.
#
#  CommandPost is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  CommandPost is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with CommandPost.  If not, see <http://www.gnu.org/licenses/>.
#

class UsersController < ApplicationController
  before_filter :setup
  
  def setup
    @section = 'users'
  end
  
  # GET /users
  # GET /users.xml
  def index
    @users = User.find(:all, :order => 'name')
    @roles = Role.find(:all, :order => 'name')

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @roles }
    end
  end
  
  def show
    @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @report_type }
    end
  end

  def edit
    @user = User.find(params[:id])
  end
  
  # render new.rhtml
  def new
  end

  def create
    cookies.delete :auth_token
    # protects against session fixation attacks, wreaks havoc with 
    # request forgery protection.
    # uncomment at your own risk
    # reset_session
    User.transaction do
      @user = User.new(params[:user])
      @user.save
      RolesUser.new(:user => @user, :role => Role.find_by_name('Guests'), :created_by => @user).save!
    end
    if @user.errors.empty?
      self.current_user = @user
      redirect_back_or_default('/')
      flash[:notice] = "Account created!"
    else
      render :action => 'new'
    end
  end

  # PUT /users/1
  # PUT /users/1.xml
  def update
    @user = User.find(params[:id])
    @user.created_by = current_user

    respond_to do |format|
      if @report_type.update_attributes(params[:report_type])
        flash[:notice] = 'User was successfully updated.'
        format.html { list_types }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit", :layout => false }
        format.xml  { render :xml => @report_type.errors, :status => :unprocessable_entity }
      end
    end
  end

end
